// 核心组件加载控制器 - 暴露为全局变量
window.componentLoader = {
    // 组件存储对象
    components: {
        header: {
            url: '/assets/components/header.html',
            cache: null
        },
        footer: {
            url: '/assets/components/footer.html',
            cache: null
        }
    },

    /**
     * 加载组件
     * @param {string} componentName 组件名称(header/footer)
     * @param {Element} targetElement 目标DOM元素
     * @param {Function} callback 加载完成回调
     */
    loadComponent: function(name, container, callback) {
        const component = this.components[name];
        if (!component) {
            console.error(`Component ${name} not found`);
            return;
        }
        
        // 使用缓存的组件
        if (component.cache) {
            container.innerHTML = component.cache;
            callback && callback();
            return;
        }
        
        // 从服务器加载组件
        this.fetchComponent(name)
            .then(html => {
                component.cache = html;
                container.innerHTML = html;
                callback && callback();
            })
            .catch(error => {
                console.error(`Failed to load component ${name}:`, error);
                // 使用备用HTML
                container.innerHTML = this.getFallbackHTML(name);
                callback && callback();
            });
    },
    
    /**
     * 从服务器获取组件
     */
    fetchComponent: function(name) {
        return fetch(this.components[name].url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.text();
            });
    },

    /**
     * 内联HTML备用方案(仅在加载失败时使用)
     */
    getFallbackHTML(componentName) {
        // 简化后的备用HTML，只保留基本结构
        switch(componentName) {
            case 'header':
                return `
                    <div class="fallback-header">
                        <nav>
                            <ul>
                                <li><a href="/">首页</a></li>
                                <li><a href="/pages/vtb-account.html">VTB开户</a></li>
                                <li><a href="/pages/china-russia-payment.html">中俄收付款</a></li>
                                <li><a href="/pages/global-payment.html">全球结算</a></li>
                                <li><a href="/pages/contact.html">联系我们</a></li>
                            </ul>
                        </nav>
                    </div>
                `;
            case 'footer':
                return `
                    <div class="fallback-footer">
                        <p>© 2025 VTB银行开户服务. 保留所有权利.</p>
                    </div>
                `;
            default:
                return '';
        }
    },

    /**
     * 初始化导航激活状态
     */
    initNavActiveState() {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.main-nav a');
        
        navLinks.forEach(link => {
            if (link.getAttribute('href') === currentPath) {
                link.classList.add('active');
                
                // 添加激活动画
                link.style.transition = 'all 0.3s ease';
                link.style.transform = 'scale(1.05)';
                setTimeout(() => {
                    link.style.transform = 'scale(1)';
                }, 300);
            }
        });
    },

    /**
     * 初始化语言切换功能
     */
    initLanguageSwitcher() {
        const langButtons = document.querySelectorAll('.language-switcher button');
        const currentLang = document.documentElement.lang || 'zh-CN';
        
        // 设置当前语言按钮激活状态
        langButtons.forEach(button => {
            if (button.dataset.language === currentLang) {
                button.classList.add('active');
            }
            button.addEventListener('click', () => {
                // 移除所有按钮激活状态
                langButtons.forEach(btn => btn.classList.remove('active'));
                // 添加当前按钮激活状态
                button.classList.add('active');
                // 更新HTML语言属性
                document.documentElement.lang = button.dataset.language;
                // 触发语言切换事件(可被翻译系统监听)
                document.dispatchEvent(new CustomEvent('languageChanged', {
                    detail: { language: button.dataset.language }
                }));
            });
        });
    },

    /**
     * 初始化移动端导航
     */
    initMobileNav() {
        // 创建移动导航切换按钮
        this.createMobileNavToggle();
        
        // 初始检查
        this.updateMobileNavState();
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => this.updateMobileNavState());
        
        // 监听导航切换
        document.querySelector('.mobile-nav-toggle')
            .addEventListener('click', () => {
                document.querySelector('.main-nav').classList.toggle('mobile-active');
            });
    },
    
    /**
     * 创建移动导航切换按钮
     */
    createMobileNavToggle() {
        if (document.querySelector('.mobile-nav-toggle')) return;
        
        const header = document.querySelector('header');
        if (!header) return;
        
        const toggleBtn = document.createElement('button');
        toggleBtn.className = 'mobile-nav-toggle';
        toggleBtn.innerHTML = `
            <span></span>
            <span></span>
            <span></span>
        `;
        
        header.insertBefore(toggleBtn, header.firstChild);
    },
    
    /**
     * 更新移动导航状态
     */
    updateMobileNavState() {
        const nav = document.querySelector('.main-nav');
        const toggleBtn = document.querySelector('.mobile-nav-toggle');
        
        if (!nav || !toggleBtn) return;
        
        // 响应式断点
        const breakpoint = 768;
        
        if (window.innerWidth < breakpoint) {
            // 移动视图
            toggleBtn.style.display = 'block';
            nav.classList.add('mobile-nav');
            nav.classList.remove('desktop-nav');
            
            // 默认隐藏移动导航
            if (!nav.classList.contains('mobile-active')) {
                nav.style.display = 'none';
            }
        } else {
            // 桌面视图
            toggleBtn.style.display = 'none';
            nav.classList.remove('mobile-nav', 'mobile-active');
            nav.classList.add('desktop-nav');
            nav.style.display = 'block';
        }
    },
    
    /**
     * 清理移动导航
     */
    cleanupMobileNav() {
        const toggleBtn = document.querySelector('.mobile-nav-toggle');
        if (toggleBtn) {
            toggleBtn.remove();
        }
        
        const nav = document.querySelector('.main-nav');
        if (nav) {
            nav.classList.remove('mobile-nav', 'mobile-active', 'desktop-nav');
            nav.style.display = '';
        }
    }
};

// 添加必要的CSS样式
(function() {
    const style = document.createElement('style');
    style.textContent = `
        /* 移动导航切换按钮 */
        .mobile-nav-toggle {
            display: none;
            position: absolute;
            top: 20px;
            right: 20px;
            background: none;
            border: none;
            cursor: pointer;
            z-index: 1000;
            padding: 10px;
        }
        
        .mobile-nav-toggle span {
            display: block;
            width: 25px;
            height: 3px;
            background-color: white;
            margin: 5px 0;
            transition: all 0.3s ease;
        }
        
        .mobile-nav-toggle.active span:nth-child(1) {
            transform: rotate(45deg) translate(5px, 5px);
        }
        
        .mobile-nav-toggle.active span:nth-child(2) {
            opacity: 0;
        }
        
        .mobile-nav-toggle.active span:nth-child(3) {
            transform: rotate(-45deg) translate(5px, -5px);
        }
        
        /* 移动导航菜单 */
        .main-nav.mobile-nav {
            display: none;
            position: absolute;
            top: 70px;
            left: 0;
            width: 100%;
            background-color: #fff;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
            z-index: 999;
        }
        
        .main-nav.mobile-nav.active {
            display: block;
        }
        
        .main-nav.mobile-nav ul {
            display: block;
            padding: 0;
            margin: 0;
        }
        
        .main-nav.mobile-nav li {
            display: block;
            border-bottom: 1px solid #eee;
        }
        
        .main-nav.mobile-nav li:last-child {
            border-bottom: none;
        }
        
        .main-nav.mobile-nav a {
            display: block;
            padding: 15px 20px;
            color: #333;
            text-decoration: none;
        }
        
        /* 桌面导航 */
        .main-nav.desktop-nav ul {
            display: flex;
            list-style: none;
            margin: 0;
            padding: 0;
        }
        
        .main-nav.desktop-nav li {
            margin-right: 20px;
        }
        
        .main-nav.desktop-nav a {
            color: white;
            text-decoration: none;
        }
        
        /* 导航激活状态 */
        .main-nav a.active {
            color: #FF9800;
            font-weight: bold;
        }
        
        /* 语言切换按钮 */
        .language-switcher button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            padding: 5px 10px;
            margin-right: 5px;
        }
        
        .language-switcher button.active {
            background-color: rgba(255,255,255,0.2);
            border-radius: 4px;
        }
        
        /* 备用组件样式 */
        .fallback-header, .fallback-footer {
            padding: 15px;
            background-color: #f8f8f8;
            border: 1px solid #eee;
            text-align: center;
        }
    `;
    document.head.appendChild(style);
})();